package com.ticket.sass.admin.controller;


import com.alibaba.excel.EasyExcel;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.ticket.sass.admin.annotation.AuthIgnore;
import com.ticket.sass.admin.annotation.Loggable;
import com.ticket.sass.admin.annotation.Module;
import com.ticket.sass.admin.business.FileUpLoadBusiness;
import com.ticket.sass.admin.business.OrderCommoditiesBusiness;
import com.ticket.sass.admin.dto.input.order.DispatchInput;
import com.ticket.sass.admin.dto.input.order.OrderCommodityListInput;
import com.ticket.sass.admin.dto.input.order.PrintInput;
import com.ticket.sass.admin.dto.input.order.RefundInput;
import com.ticket.sass.admin.dto.output.order.*;
import com.ticket.sass.admin.dto.output.order.export.OrderCommodityListExport;
import com.ticket.sass.admin.handler.IdentityInput;
import com.ticket.sass.admin.manager.ThreadLocalIdInputHolderManager;
import com.ticket.sass.admin.model.ResultModel;
import com.ticket.sass.common.exception.enums.ErrorCode;
import com.ticket.sass.common.exception.exception.BadRequestException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ywb
 * @since 2024-03-07
 */
@RestController
@AllArgsConstructor
@ApiSupport(order = 16)
@Api(tags = {"卖品订单数据-模块"})
@RequestMapping("/commodity-orders")
public class OrderCommoditiesController {
    final OrderCommoditiesBusiness business;
    final FileUpLoadBusiness fileUpLoadBusiness;
    
    @ApiOperation("列表")
    @GetMapping
    public ResultModel<OrderDataModel<OrderCommodityListOutput>> list(
        @Valid OrderCommodityListInput input
    ) {
        return ResultModel.success(
            business.list(input)
        );
    }
    
    @ApiOperation("退单")
    @PostMapping("/refund")
    @Loggable(module = Module.ORDER, desc = "卖品订单退单")
    public ResultModel<String> refund(
        @RequestBody @Valid RefundInput input
    ) {
        business.refund(input);
        return ResultModel.success();
    }
    
    @ApiOperation("打印")
    @PostMapping("/print")
    @Loggable(module = Module.ORDER, desc = "卖品订单打印")
    public ResultModel<String> print(
        @RequestBody @Valid PrintInput input
    ) {
        business.print(input);
        return ResultModel.success();
    }
    
    @ApiOperation("配送")
    @PutMapping("/dispatch")
    @Loggable(module = Module.ORDER, desc = "卖品订单配送")
    public ResultModel<String> dispatch(
        @RequestBody @Valid DispatchInput input
    ) {
        business.dispatch(input);
        return ResultModel.success();
    }
    
    @AuthIgnore
    @ApiOperation("导出")
    @GetMapping("/export")
    public void exportCouponCodes(
        @Valid OrderCommodityListInput input,
        HttpServletResponse response,
        @Valid Long cinemaId,
        @Valid String token
    ) throws IOException {
        if (Objects.isNull(cinemaId)){
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "影院ID不能为空"
            );
        }
        if (!fileUpLoadBusiness.existExportToken(token, "order-commodity")) {
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "token过期"
            );
        }
        
        // 设置请求参数
        input.setPageNum(1);
        input.setPageSize(1000);
        
        IdentityInput value = ThreadLocalIdInputHolderManager.getValue();
        value.setCinemaId(cinemaId);
        
        ThreadLocalIdInputHolderManager.setValue(value);
        
        // 调用业务逻辑获取数据
        List<OrderCommodityListOutput> list = business.list(input).getList();
        
        List<OrderCommodityListExport> exports = convertToExcelData(list);
        
        // 设置响应头
        // 设置响应头，指定Content-Type和文件名
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(System.currentTimeMillis() + "", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        // 写入数据到Excel文件
        try (OutputStream outputStream = response.getOutputStream()) {
            EasyExcel.write(outputStream, OrderCommodityListExport.class).sheet("卖品订单").doWrite(exports);
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "导出失败"
            );
        }
    }
    
    public List<OrderCommodityListExport> convertToExcelData(List<OrderCommodityListOutput> list) {
        return list.stream().map(this::convert).collect(Collectors.toList());
    }
    
    private OrderCommodityListExport convert(OrderCommodityListOutput output) {
        OrderCommodityListExport export = new OrderCommodityListExport();
        
        // 根据属性名进行赋值，这里假设CommodityOutput类有一个方法getCommodityInfo返回卖品信息
        String commodityInfo = output.getCommodities().stream()
            .map(CommodityOutput::getCommodityInfo)
            .collect(Collectors.joining(System.lineSeparator())); // 如果有多个商品，可以用逗号分隔
        
        export.setCommodityInfo(commodityInfo);
        export.setTakeCode(output.getTakeCode());
        export.setOrderNo(output.getOrderNo());
        export.setCellphone(output.getCellphone());
//        export.setCouponInfo(output.getCoupons().isEmpty() ? "" : output.getCoupons().get(0).getCouponInfo()); // 假设只有一个优惠券
        export.setDispatchInfo(output.getDispatchInfo() != null ? output.getDispatchInfo().getInfo() : "暂不支持"); // 假设DispatchInfoOutput有一个getInfo方法
      
        export.setCreateAt(output.getCreatedAt().toString().replace("T", " "));
        export.setPayDatetime(output.getPayTime().toString().replace("T", " "));
        
        export.setPrintNum(output.getPrintNum());
        export.setPayPrice(output.getPayPrice());
        
        // 支付方式和支付状态根据枚举值转换为字符串
        String payType = convertPayTypeToString(output.getPayType());
        String payStatus = convertPayStatusToString(output.getPayStatus());
        
        export.setPayType(payType);
        export.setPayStatus(payStatus);
        
        return export;
    }
    
    // 将支付类型转换为字符串
    private String convertPayTypeToString(Integer payType) {
        // 这里需要根据实际的枚举值来转换
        switch (payType) {
            case 1:
                return "微信支付";
            case 2:
                return "支付宝";
            case 3:
                return "会员卡";
            default:
                return "未知";
        }
    }
    
    // 将支付状态转换为字符串
    private String convertPayStatusToString(Integer payStatus) {
        // 这里需要根据实际的枚举值来转换
        switch (payStatus) {
            case 0:
                return "未支付";
            case 1:
                return "支付中";
            case 2:
                return "已支付";
            case 3:
                return "支付失败";
            case 4:
                return "退款中";
            case 5:
                return "已退款";
            default:
                return "未知";
        }
    }
}
